package com.dtm.client.thread;



import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;

import javax.jmdns.JmDNS;
import javax.jmdns.ServiceEvent;
import javax.jmdns.ServiceListener;

import android.content.Context;
import android.os.Handler;
import android.util.Log;

public class SearchHostThread implements Runnable {
	
	
	android.net.wifi.WifiManager.MulticastLock lock;
	
	private DataInputStream is;
	private DataOutputStream os;
	private Socket sc;

	private Context context;

	private JmDNS jmdns;

	private ServiceListener listener;

	private String type = "_workstation._tcp.local.";

	private OnServerChangeListener foundListener;

	private Handler handler;
	
	public SearchHostThread(Context context, OnServerChangeListener foundListener, Handler handler) {
		this.handler = handler;
		this.foundListener = foundListener;
		this.context = context;
	}

	public void run() {
		android.net.wifi.WifiManager wifi = (android.net.wifi.WifiManager) context.getSystemService(android.content.Context.WIFI_SERVICE);
        lock = wifi.createMulticastLock("mylockthereturn");
        lock.setReferenceCounted(true);
        lock.acquire();
        try { 
        	String ip = Utils.getIPAddress(true);
        	InetAddress bindingAddress = InetAddress.getByName(ip);
            jmdns = JmDNS.create(bindingAddress);
            jmdns.addServiceListener(type, listener = new ServiceListener() {

                @Override
                public void serviceResolved(final ServiceEvent ev) {
                	handler.post(new Runnable() {
						@Override
						public void run() {
							foundListener.onFound(ev);
						}
					});
                }

                @Override
                public void serviceRemoved(final ServiceEvent ev) {
                	handler.post(new Runnable() {
						@Override
						public void run() {
							foundListener.onRemove(ev);
						}
					});
                    
                }

                @Override
                public void serviceAdded(ServiceEvent event) {
                    jmdns.requestServiceInfo(event.getType(), event.getName(),
                            1);

                }
            });

        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
	}

}
